<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="项目阶段" prop="projectPhase">
        <el-select v-model="queryParams.projectPhase" placeholder="请选择项目阶段" clearable>
          <el-option label="售前" value="售前" />
          <el-option label="开发" value="开发" />
          <el-option label="验收" value="验收" />
        </el-select>
      </el-form-item>
      <!-- 在搜索表单中添加日期范围选择器 -->
      <el-form-item label="签订日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          style="width: 240px;"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="收款状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择收款状态" clearable>
          <el-option label="未收款" value="未收款" />
          <el-option label="已收款" value="已收款" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格标题栏 -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h3 style="margin: 0; font-size: 16px; font-weight: 600; color: #303133;">项目信息管理</h3>
      <el-button type="primary" icon="Plus" @click="handleAdd">新增项目</el-button>
    </div>

    <!-- 主表 + 子表展开 -->
    <el-table ref="managementTable" v-loading="loading" :data="managementList" row-key="id"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
              :cell-style="{ padding: '8px 0' }"
              :row-class-name="getRowClassName"
              @row-click="handleRowClick">

      <!-- 子表展开 -->
      <el-table-column type="expand">
        <template v-slot="props">
          <div style="display: flex; justify-content: center;">
            <el-table :data="props.row.projectStageList || []" border size="small"
                      :header-cell-style="{ background: '#f0f9ff', color: '#1e40af', fontWeight: 'bold' }"
                      :cell-style="getSubTableCellStyle"
                      :row-class-name="getSubTableRowClassName">
              <el-table-column prop="stage" label="阶段" width="150" align="center" show-overflow-tooltip/>
              <el-table-column prop="amount" label="金额" width="100" align="center"/>
              <el-table-column prop="remark" label="备注" width="180" align="center" show-overflow-tooltip/>
              <el-table-column prop="paymentStatus" label="收款状态" width="100" align="center"/>
              <el-table-column prop="dateReceipt" label="收款节点" width="120" align="center"/>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <!-- 主表字段 -->
      <el-table-column label="客户名称" align="left" prop="customerName" show-overflow-tooltip />
      <el-table-column label="项目名称" align="left" prop="projectName" show-overflow-tooltip />
      <el-table-column label="合同名称" align="left" prop="contractName" show-overflow-tooltip />
      <el-table-column label="合同状态" align="center" prop="status" />
      <el-table-column label="签订日期" align="center" prop="signingDate">
        <template v-slot="scope">
          <span v-if="scope.row.status === '已签订'">{{ scope.row.signingDate }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="合同金额" align="center" prop="contractAmount" />
      <!-- <el-table-column label="已发生项目成本" align="center" prop="projectCost" /> -->
      <el-table-column label="项目阶段" align="center" prop="projectPhase">
        <template v-slot="scope">
          <el-tag
            :type="getProjectPhaseTagType(scope.row.projectPhase)"
            size="small">
            {{ scope.row.projectPhase }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template v-slot="{ row }">
          <div style="display: flex; justify-content: center; gap: 8px;">
            <el-button size="small" type="primary" icon="Edit" @click="handleUpdate(row)">修改</el-button>
            <el-button size="small" type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>

    <!-- 添加 / 修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="managementRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerName"><el-input v-model="form.customerName"/></el-form-item>
        <el-form-item label="项目名称" prop="projectName"><el-input v-model="form.projectName"/></el-form-item>
        <el-form-item label="合同名称" prop="contractName"><el-input v-model="form.contractName"/></el-form-item>
        <el-form-item label="合同状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择合同状态" @change="handleContractStatusChange">
            <el-option label="已签订" value="已签订"/>
            <el-option label="未签订" value="未签订"/>
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期" prop="signingDate" v-if="form.status === '已签订'">
          <el-date-picker v-model="form.signingDate" type="date" placeholder="请选择签订日期"
                          value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="项目阶段" prop="projectPhase">
          <el-select v-model="form.projectPhase" placeholder="请选择项目阶段">
            <el-option label="售前" value="售前"/>
            <el-option label="开发" value="开发"/>
            <el-option label="验收" value="验收"/>
          </el-select>
        </el-form-item>

        <!-- 子表操作按钮 -->
        <el-divider content-position="center">项目阶段明细</el-divider>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
          <span style="font-size: 14px; font-weight: 500; color: #606266;">阶段明细管理</span>
          <div style="display: flex; gap: 8px;">
            <el-button size="small" type="primary" icon="Plus" @click="handleAddProjectStage" plain>新增阶段</el-button>
            <el-button size="small" type="danger" icon="Delete" @click="handleDeleteProjectStage" plain>删除选中</el-button>
          </div>
        </div>

        <!-- 子表 -->
        <el-table :data="projectStageList" border size="small"
                  @selection-change="handleProjectStageSelectionChange" ref="projectStage"
                  :header-cell-style="{ background: '#f0f9ff', color: '#1e40af', fontWeight: 'bold' }"
                  :cell-style="{ padding: '6px 0' }">
          <el-table-column type="selection" width="50"/>
          <el-table-column label="阶段" prop="stage" width="150" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.stage" placeholder="必填"/>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="120" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.amount" placeholder="必填"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="180" align="center">
            <template v-slot="scope"><el-input v-model="scope.row.remark"/></template>
          </el-table-column>
          <el-table-column label="收款状态" prop="paymentStatus" width="120" align="center">
            <template v-slot="scope">
              <el-select v-model="scope.row.paymentStatus" placeholder="必填" >
                <el-option label="未收款" value="未收款"/>
                <el-option label="已收款" value="已收款"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="收款节点" prop="dateReceipt" width="140" align="center">
            <template v-slot="scope">
              <el-date-picker v-model="scope.row.dateReceipt" type="date"
                              placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listManagement, getManagement, delManagement, addManagement, updateManagement } from "@/api/management/management";

export default {
  data() {
    return {
      managementList: [],
      projectStageList: [],
      open: false,
      loading: false,
      showSearch: true,
      checkedProjectStage: [],
      total: 0,
      title: "",

      // 新增：日期范围数据
      dateRange: [], // 签订日期范围

      form: {
        id: null,
        customerName: "",
        projectName: "",
        contractName: "",
        status: "",
        signingDate: "",
        projectPhase: ""
      },
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        customerName: "",
        projectName: "",
        projectPhase: "",
        paymentStatus: "",
        // 新增：日期查询参数
        startDate: "", // 开始日期
        endDate: ""    // 结束日期
      },
      rules: {
        customerName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        contractName: [{ required: true, message: "合同名称不能为空", trigger: "blur" }],
        status: [{ required: true, message: "合同状态不能为空", trigger: "blur" }],
        signingDate: [{
          required: true,
          message: "签订日期不能为空",
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (this.form.status === '已签订' && !value) {
              callback(new Error('已签订状态下签订日期不能为空'));
            } else {
              callback();
            }
          }
        }],
        projectPhase: [{ required: true, message: "项目阶段不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      // 修改：使用当前查询参数调用后端接口
      listManagement(this.queryParams)
        .then(res => {
          if (res && res.data) {
            this.managementList = (res.data.rows || []).map(item => ({
              ...item,
              projectStageList: item.stage || []
            }));
            this.total = res.data.total || 0;
          }
        })
        .finally(() => this.loading = false);
    },
    // 日期范围变化处理
    handleDateChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.queryParams.startDate = dateRange[0]
        this.queryParams.endDate = dateRange[1]
      } else {
        this.queryParams.startDate = ""
        this.queryParams.endDate = ""
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(); // 修改：重新请求数据
    },
    resetQuery() {
      this.$refs.queryRef.resetFields();
      this.queryParams = {
        pageNum: 1,
        pageSize: 30,
        customerName: "",
        projectName: "",
        projectPhase: "",
        paymentStatus: "",
        startDate: "",
        endDate: ""
      };
      // 清空日期选择器的值
      this.dateRange = [];
      this.getList(); // 修改：重新请求数据
    },
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.queryParams.pageNum = 1;
      this.getList(); // 修改：重新请求数据
    },
    handleCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.getList(); // 修改：重新请求数据
    },
    handleAdd() { this.reset(); this.open = true; this.title = "添加项目信息"; },
    handleUpdate(row) {
      const _id = row.id;
      if (!_id) return this.$message.error("请选择数据");

      // 先重置表单，确保清空之前的数据
      this.reset();

      getManagement(_id).then(res => {
        console.log("获取项目详情响应:", res); // 调试信息
        const data = res.data || {};
        console.log("项目数据:", data); // 调试信息

        // 使用 $nextTick 确保 DOM 更新后再填充数据
        this.$nextTick(() => {
          // 显式赋值，确保 Vue 响应式
          this.form = {
            id: data.id || null,
            customerName: data.customerName || "",
            projectName: data.projectName || "",
            contractName: data.contractName || "",
            status: data.status || "",
            signingDate: data.signingDate || "",
            projectPhase: data.projectPhase || ""
          };

          // 处理项目阶段明细数据
          this.projectStageList = data.stage || [];

          console.log("填充后的表单数据:", this.form); // 调试信息
          console.log("项目阶段明细:", this.projectStageList); // 调试信息
        });

        this.open = true;
        this.title = "修改项目信息";
      }).catch(err => {
        console.error("获取项目详情失败:", err);
        this.$message.error("获取项目详情失败");
      });
    },

    submitForm() {
      this.$refs.managementRef.validate(valid => {
        if (!valid) return;

        // 验证项目阶段明细必填字段
        const invalidStages = this.projectStageList.filter(stage =>
          !stage.stage || !stage.amount || !stage.paymentStatus
        );

        if (invalidStages.length > 0) {
          this.$message.error("项目阶段明细中的阶段、金额、收款状态为必填项，请完善后再提交");
          return;
        }

        this.form.stage = this.projectStageList.map(item => ({ ...item }));

        // 添加项目时带上userid
        const submitData = { ...this.form };
        if (!submitData.id) {
          // 新增项目时添加userid
          submitData.userid = this.$store.getters.name; // 使用当前登录用户名作为userid
        }

        const req = submitData.id ? updateManagement(submitData) : addManagement(submitData);
        req.then(() => {
          this.$message.success(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    cancel() { this.open = false; this.reset(); },
    reset() {
      this.form = { id: null, customerName: "", projectName: "", contractName: "", status: "", signingDate: "", projectPhase: "" };
      this.projectStageList = [];
      this.$refs.managementRef && this.$refs.managementRef.resetFields();
    },
    handleDelete(row) {
      const _id = row.id;
      if (!_id) return this.$message.error("请选择要删除的数据");
      this.$confirm(`是否确认删除该项目？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          this.loading = true;
          delManagement([_id]).then(() => {
            this.$message.success("删除成功");
            this.getList();
          }).finally(() => this.loading = false);
        }).catch(() => {});
    },
    handleAddProjectStage() {
      this.projectStageList.push({ stage: "", amount: "", remark: "", paymentStatus: "", dateReceipt: "" });
      this.updateStageIndex();
    },
    handleDeleteProjectStage() {
      if (!this.checkedProjectStage.length) return this.$message.error("请先选择要删除的子表数据");
      this.$confirm(`是否删除选中的 ${this.checkedProjectStage.length} 条项目阶段明细？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          this.projectStageList = this.projectStageList.filter(item => !this.checkedProjectStage.includes(item.id));
          this.checkedProjectStage = [];
          this.updateStageIndex();
          this.$message.success("删除成功");
        }).catch(() => {});
    },
    handleProjectStageSelectionChange(selection) { this.checkedProjectStage = selection.map(item => item.id); },
    updateStageIndex() { this.projectStageList.forEach((item, index) => item.index = index + 1); },
    handleContractStatusChange(value) {
      if (value === '未签订') {
        // 未签订时设置默认日期为1900-01-01
        this.form.signingDate = '1900-01-01';
      } else if (value === '已签订') {
        // 已签订时清空日期，让用户手动选择
        this.form.signingDate = '';
      }
    },
    getProjectPhaseTagType(phase) {
      const phaseMap = {
        '售前': 'warning',
        '开发': 'primary',
        '验收': 'success',
        '开票': 'info'
      };
      return phaseMap[phase] || 'info';
    },
    getRowClassName({ row }) {
      // 合同状态=未签订 且 项目阶段非售前 时添加警告样式
      if (row.status === '未签订' && row.projectPhase && row.projectPhase !== '售前') {
        return 'warning-row';
      }
      return '';
    },
    handleRowClick(row, column, event) {
      // 如果点击的是操作按钮，不展开行
      if (event.target.closest('.action-buttons') || event.target.closest('.el-button')) {
        return;
      }

      // 切换行的展开状态
      this.$refs.managementTable.toggleRowExpansion(row);
    },
    handleExport() { this.$download("management/management/export", { ...this.queryParams }, `management_${Date.now()}.xlsx`); },
    getSubTableCellStyle({ row, column, rowIndex, columnIndex }) {
      // 为已收款状态的行添加浅绿色背景
      if (row.paymentStatus === '已收款') {
        return {
          padding: '6px 0',
          backgroundColor: '#f0f9f0' // 浅绿色背景
        };
      }
      return { padding: '6px 0' };
    },
    getSubTableRowClassName({ row, rowIndex }) {
      // 为已收款状态的行添加CSS类名
      if (row.paymentStatus === '已收款') {
        return 'paid-row';
      }
      return '';
    }
    // 删除 applyFilters 方法，因为现在由后端处理筛选
  }
};
</script>

<style>
.warning-row {
  background-color: rgba(255, 182, 193, 0.1) !important;
}

.warning-row:hover {
  background-color: rgba(255, 182, 193, 0.5) !important;
}

.warning-row td {
  background-color: rgba(255, 182, 193, 0.3) !important;
}

.warning-row:hover td {
  background-color: rgba(255, 182, 193, 0.5) !important;
}

/* 行点击样式 */
.el-table__row {
  cursor: pointer;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}

/* 已收款状态的行样式 */
.paid-row {
  background-color: #f0f9f0 !important;
}

.paid-row:hover {
  background-color: #e8f5e8 !important;
}

.paid-row td {
  background-color: #f0f9f0 !important;
}

.paid-row:hover td {
  background-color: #e8f5e8 !important;
}
</style>
